<?php
namespace Home\Controller;
use Think\Controller;
use Common\Controller\HomeController;
use Common\Api\CommissionApi;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends HomeController
{
    /**
     * 系统首页
     * @author xiaojing
     */
    public function index()
    {
        $user_id = is_login();

        if($user_id){

            $modifypricehistoryData = $this->getUserModifypricehistory();// 调价历史记录

            $this->assign('modifypricehistoryData',$modifypricehistoryData);
        }

        hook('homeIndex');

        $default_url = C('DEFUALT_HOME_URL');//获得配置，如果为空则显示聚合，否则跳转

        if ($default_url != ''&&strtolower($default_url)!='home/index/index') {
            redirect(get_nav_url($default_url));
        }
        $this->display();
    }

    public function home()
    {

        hook('homeIndex');

        $default_url = C('DEFUALT_HOME_URL');//获得配置，如果为空则显示聚合，否则跳转

        if ($default_url != ''&&strtolower($default_url)!='home/index/index') {
            redirect(get_nav_url($default_url));
        }

        $show_blocks = get_kanban_config('BLOCK', 'enable', array(), 'Home');

        $this->assign('showBlocks', $show_blocks);

        $enter = modC('ENTER_URL', '', 'Home');

        $this->assign('enter', get_nav_url($enter));

        $this->display();
    }

    /**
     * 使用帮助 页面展示
     * @author xiaojing
     */
    public function help(){
        $this->display();
    }

    /**
     * 授权 帮助 页
     * @author xiaojing
     */
    public function authorizeHelp(){
        $this->display();
    }

    /**
     * 账户 管理 展示
     * @author xiaojing
     */
    public function accountAdministration(){
        $userInfo = $this->userInfo();// 用户信息
        $this->assign('userInfo',$userInfo);
        $this->display();
    }

    /**
     * 利润 计算 展示
     * @author xiaojing
     */
    public function commission(){
        $this->display();
    }

    /**
     * 利润 计算 帮助 查询页
     * @author xiaojing
     */
    public function profit(){
        $this->display();
    }

    /**
     * 利润 计算 调用 api
     * @author xiaojing
     */
    public function commissionApi(){

        $dataArr           = json_decode(I('post.data'),true);

        $amzCommissionRate = $dataArr['amzCommissionRate'];//佣金比率

        $amzMarket         = $dataArr['amzMarket'];//平台

        $txtCost           = $dataArr['txtCost']; //产品成本价

        $txtPrice          = $dataArr['txtPrice']; //产品售价

        $txtFreightCost    = $dataArr['txtFreightCost']; //物流单价

        $txtHeight         = $dataArr['txtHeight']; //产品尺寸

        $txtWidth          = $dataArr['txtWidth'];//产品尺寸

        $txtLength         = $dataArr['txtLength'] ;//产品尺寸

        $txtInRMB          = $dataArr['txtInRMB']; //将币种统一为人民币

        $txtRate           = $dataArr['txtRate']; //汇率

        $txtWeightAcutal   = $dataArr['txtWeightAcutal']; //产品重量

        $test              = new CommissionApi();

        $test->market     = $amzMarket;//Amazon平台


        if(!isset($txtRate) or $txtRate==""){
            $test->updateCurrency();
        }else{
            $test->currencyRate = $txtRate;
        }

        $test->commission    = isset($amzCommissionRate)?$amzCommissionRate:"";//0.15; //拥金比例

        $test->cost           = isset($txtCost)?$txtCost:"";//11;     //成本

        $test->price          = isset($txtPrice)?$txtPrice:"";//11;    //售价

        $test->productLength = isset($txtLength)?$txtLength:"";//16.74; // 长

        $test->productWidth  = isset($txtWidth)?$txtWidth:""; //9.65 ;  // 宽

        $test->productHeight = isset($txtHeight)?$txtHeight:"";//6.604; // 高

        $test->weightActual  = isset($txtWeightAcutal)?$txtWeightAcutal:"";//0.321; //实际重

        $test->freightCost   = isset($txtFreightCost)?$txtFreightCost:""; //40;  //物流单价

        if(!isset($txtInRMB) or $txtInRMB == ""){
            $respon = array('code' => '200',
                'msg' => 'Success',
                'value'  => array(
                    "calcStandSize"=> $test->calcStandSize(),
                    "calcCost"=> $test->calcCost(),
                    "calcShipping"=> $test->calcShipping(),
                    "calcCommission"=> $test->calcCommission(),
                    "calcFBA"=>$test->calcFBA(),
                    "calcPrice"=>$test->calcPrice(),
                    "calcMargin"=>$test->calcMargin(),
                    "calcMarginPercent"=>$test->calcMarginPercent(),
                    "calcStatus"=>$test->calcStatus(),
                    "calcPriceOnMarginPercent"=>$test->calcPriceOnMarginPercent(),
                    "calcBtnCurrencySymbol"=>"$",
                    "calcCurrencySymbol"=>$test->calcCurrencySymbol(),
                    "calcCurrencyRate"=>$test->calcCurrencyRate()
                )
            );
        }else{
            $respon = array('code' => '200',
                'msg' => 'Success',
                'value'  => array(
                    "calcStandSize"=>$test->calcStandSize(),
                    "calcCost"=>$test->calcCost(),
                    "calcShipping"=>$test->convertFromCurrency($test->calcShipping(),
                        "RMB",
                        $test->calcCurrencyRate()),
                    "calcCommission"=>$test->convertFromCurrency($test->calcCommission(),
                        "RMB",
                        $test->calcCurrencyRate()),
                    "calcFBA"=>$test->convertFromCurrency($test->calcFBA(),
                        "RMB",
                        $test->calcCurrencyRate()),
                    "calcPrice"=>$test->convertFromCurrency($test->calcPrice(),
                        "RMB",
                        $test->calcCurrencyRate()),
                    "calcMargin"=>$test->convertFromCurrency($test->calcMargin(),
                        "RMB",
                        $test->calcCurrencyRate()),
                    "calcMarginPercent"=>$test->calcMarginPercent(),
                    "calcStatus"=>$test->calcStatus(),
                    "calcPriceOnMarginPercent"=>$test->calcPriceOnMarginPercent(),
                    //statr endit xiaojing 2016-05-07
//                  "calcBtnCurrencySymbol"=>$test->calcBtnCurrencySymbol(),
                    "calcBtnCurrencySymbol"=>"¥",
                    //statr endit xiaojing 2016-05-07
                    "calcCurrencySymbol"=>$test->calcCurrencySymbol(),
                    "calcCurrencyRate"=>$test->calcCurrencyRate()
                )
            );
        }
        if(isset($dataArr['txtMLL']) && $dataArr['txtMLL']!=''){

            $respon['value']['calcMarginPercent'] = $txtPrice;

            $respon['value']['calcPrice'] = $test->calcPriceOnMarginPercent();

            $respon['value']['calcMargin'] = $test->calcPriceOnMarginMargin();

        }
        echo $this->JSON($respon);
        exit;
    }

    /**
     * 利润 计算 导出 对比 结果
     * @author xiaojing
     */
    public function exportCommissionData(){

        $dataArr = json_decode(I('post.data'),true);

        $file_path = $this->exportFileCsv($dataArr['headerbody'],$dataArr['headerTile'],'./Uploads/commission/');

        $resarr['url'] = 'http://'.$_SERVER['SERVER_NAME'].$file_path;

        $result = json_encode($resarr);

        echo $result;

        exit;

    }

    /**
     * 我的 信息 展示
     * @author xiaojing
     * @param 郑钟良<zzl@ourstu.com>
     */
    public function expandInfo()
    {


        $uid = is_login();

        $profile_group_list = $this->_profile_group_list($uid);

        if ($profile_group_list) {

            $info_list = $this->_info_list($profile_group_list[0]['id'], $uid);

            $this->assign('info_list', $info_list);

            $this->assign('profile_group_id', $profile_group_list[0]['id']);

        }
        foreach ($profile_group_list as &$v) {
            $v['fields'] = $this->_getExpandInfo($v['id']);
        }
        $this->assign('profile_group_list', $profile_group_list);
        $this->display();
    }

    /**
     * 显示某一扩展分组信息
     * @param null $profile_group_id
     * @param null $uid
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function _getExpandInfo($profile_group_id = null)
    {
        $res = D('field_group')->where(array('id' => $profile_group_id, 'status' => '1'))->find();
        if (!$res) {
            return array();
        }
        $info_list = $this->_info_list($profile_group_id);
        return $info_list;
        $this->assign('info_list', $info_list);
        $this->assign('profile_group_id', $profile_group_id);
        //dump($info_list);exit;
        $this->assign('profile_group_list', $profile_group_list);
    }

    /**
     * 扩展信息分组列表获取
     * @return mixed
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function _profile_group_list($uid = null)
    {
        $profile_group_list = array();
        $fields_list = $this->getRoleFieldIds($uid);
        if ($fields_list) {
            $fields_group_ids = D('FieldSetting')->where(array('id' => array('in', $fields_list), 'status' => '1'))->field('profile_group_id')->select();
            if ($fields_group_ids) {
                $fields_group_ids = array_unique(array_column($fields_group_ids, 'profile_group_id'));
                $map['id'] = array('in', $fields_group_ids);

                if (isset($uid) && $uid != is_login()) {
                    $map['visiable'] = 1;
                }
                $map['status'] = 1;
                $profile_group_list = D('field_group')->where($map)->order('sort asc')->select();
            }
        }
        return $profile_group_list;
    }

    /**
     * 分组下的字段信息及相应内容
     * @param null $id 扩展分组id
     * @param null $uid
     * @author xiaojing
     */
    public function _info_list($id = null, $uid = null)
    {

        $fields_list = $this->getRoleFieldIds($uid);
        $info_list = null;

        if (isset($uid) && $uid != is_login()) {
            //查看别人的扩展信息
            $field_setting_list = D('field_setting')->where(array('profile_group_id' => $id, 'status' => '1', 'visiable' => '1', 'id' => array('in', $fields_list)))->order('sort asc')->select();

            if (!$field_setting_list) {
                return null;
            }
            $map['uid'] = $uid;
        } else if (is_login()) {
            $field_setting_list = D('field_setting')->where(array('profile_group_id' => $id, 'status' => '1', 'id' => array('in', $fields_list)))->order('sort asc')->select();

            if (!$field_setting_list) {
                return null;
            }
            $map['uid'] = is_login();

        } else {
            $this->error(L('_ERROR_PLEASE_LOGIN_').L('_EXCLAMATION_'));
        }
        foreach ($field_setting_list as $val) {
            $map['field_id'] = $val['id'];
            $field = D('field')->where($map)->find();
            $val['field_content'] = $field;
            $info_list[$val['id']] = $val;
            unset($map['field_id']);
        }

        return $info_list;
    }

    private function getRoleFieldIds($uid = null)
    {
        $role_id = get_role_id($uid);

        $fields_list = S('Role_Expend_Info_' . $role_id);

        if (!$fields_list) {

            $map_role_config = getRoleConfigMap('expend_field', $role_id);

            $fields_list = D('RoleConfig')->where($map_role_config)->getField('value');

            if ($fields_list) {

                $fields_list = explode(',', $fields_list);

                S('Role_Expend_Info_' . $role_id, $fields_list, 600);

            }
        }
        return $fields_list;
    }


    /**
     * 获取 亚马逊 以下每个国家分类数据
     * @author xiaojing
     */
    public function getAmazonMarkets(){

        $post_data = array();

        $data = array();

        $url = 'http://120.76.102.10/webapi/get_amazonmarkets_api.php';

        $marketList = $this->request_post($url, $post_data);

        return json_decode($marketList,true);

    }

    /**
     *  保存亚马逊授权店铺 信息
     * @return mixed
     * @author xiaojing
     */
    public function saveAmazonauth(){

        if (IS_POST) {

            $user_info = $this->userInfo();

            $dataArr = json_decode(I('post.data'),true);

            $url = 'http://120.76.102.10/webapi/save_amazonauth_api.php';

            foreach($dataArr as $value){

                $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

                $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

                $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

                $post_data['UserSellerID'] = I('post.UserSellerID_value','');

                $post_data['UserAuthToken'] = I('post.UserAuthToken_value','');

                $post_data['UserMarketCNName'] = ($value['UserMarketCNName_value'] != '') ?  $value['UserMarketCNName_value'] : '';

                $post_data['MarketID'] = ($value['MarketID_value'] != '') ?  $value['MarketID_value'] : '';

                $data['data'] = json_encode($post_data);

                $marketList = $this->request_post($url, $data);

                print_R($marketList);

                exit;
            }
        }
    }

    /**
     * 修改亚马逊授权店铺 信息
     * @return mixed
     * @author xiaojing
     */
    public function updateAmazonauth(){
        if (IS_POST) {

            $user_info = $this->userInfo();

            $dataArr = json_decode(I('post.data'),true);

            $url = 'http://120.76.102.10/webapi/save_amazonauth_api.php';

            $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

            $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

            $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

            $post_data['RecordID'] = I('post.RecordID','');

            $post_data['IsModify'] = true;

            $post_data['IsActive'] = I('post.IsActive',0);

            $post_data['UserMarketCNName'] = I('post.UserMarketCNName','');

            $data['data'] = json_encode($post_data);

            $marketList = $this->request_post($url, $data);

            echo $marketList;

            exit;
        }
    }

    /**
     *  删除 亚马逊授权店铺 信息
     * @return mixed
     * @author xiaojing
     */
    public function deleteAmazonauth(){
        if (IS_POST) {
            $user_info = $this->userInfo();

            $dataArr = json_decode(I('post.data'),true);

            $url = 'http://120.76.102.10/webapi/delete_amazonauth_api.php';

            $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

            $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

            $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

            $post_data['RecordID'] = I('post.RecordID','');

            $post_data['MarketID'] = I('post.MarketID','');

            $data['data'] = json_encode($post_data);

            $marketList = $this->request_post($url, $data);

            echo $marketList;

            exit;
        }
    }

    /**
     * 展示当前用户亚马逊授权店铺
     * @author xiaojing
     */
    public function marketsList(){

        $post_data = array();

        $userInfo = $this->userInfo();

        $post_data['UserID'] = ($userInfo['id'] != '') ? $userInfo['id'] : "";

        $post_data['PasswordMD5'] = ($userInfo['password'] != '')?$userInfo['password'] : "";

        $post_data['UserName'] = ($userInfo['email'] != '')?$userInfo['email'] : "";

        $data['data'] = json_encode($post_data);

        $url = 'http://120.76.102.10/webapi/get_amazonauth_api.php';

        $marketList = $this->request_post($url,$data);

        $marketList = trim($marketList);

        $status = explode('","',$marketList);

        $status = explode('":"',trim($status[0],'{'));

        if($status[1] == 400){
            return array();
        }

        $days_array = explode('"values":',$marketList);

        $days_array = trim($days_array[1],'}');

        $days_array = explode('},{',$days_array);

        $arr = Array();

        foreach($days_array as $key=>$value){

            $value = trim($value,'[{');

            $value = trim($value,'}]');

            $value = explode('","',$value);

            foreach($value as  $vo){

                $vo = explode('":"',$vo);

                $arr[$key][trim($vo[0],'"')] = trim($vo[1],'"');

            }
        }

        return $arr;
    }

    /**
     * 获取  授权 状态
     * @author xiaojing
     */
    public function getMarketsStatus(){
        $marketsList = $this->marketsList(); //店铺数据;
        $marketsStatus = (count($marketsList)>0) ?  1 : 0; // true= 已授权用户,false=未授权用户
        $arr['marketsStatus'] = $marketsStatus;
        echo json_encode($arr);
        exit;
    }

    /**
     * 授权 展示
     */
    public function amazonauthMarkest(){

        $amazonMarketsInfo = $this->getAmazonMarkets();//国家 分类

        $marketsList = $this->marketsList();//店铺 数据;

        $this->assign('amazonMarketsInfo',$amazonMarketsInfo['values']);

        $this->assign('marketsList',$marketsList);

        $this->display();

    }

    /**
     * 商品数据展示
     * @return array
     * @author xiaojing
     */
    public function Product(){
        $marketsList = $this->marketsList(); //店铺数据;

        $this->assign('marketsList',$marketsList);

        $this->display();
    }

    /**
     * ajax 商品数据展示
     * @param int $page 当前页
     * @return string  JSON
     * @author xiaojing
     */
    public function getAjaxProduct(){

        $user_info = $this->userInfo();

        $dataArr = json_decode(I('post.data'),true);

        $url = 'http://120.76.102.10/webapi/get_amazon_productlist_api.php';

        $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

        $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

        $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

        $page = empty($_POST['page']) ? 1 : $_POST['page'];

        // 筛选 按 产品 状态
        if(isset($_POST['ProductStatus']) && $_POST['ProductStatus']!= ''){
            $post_data['ProductStatus'] = trim($_POST['ProductStatus']);
        }

        // 筛选 按 产品  数量
        if(isset($_POST['Quantity'])&& $_POST['Quantity']!= ''){
            $post_data['Quantity'] = trim($_POST['Quantity']);
        }

        // 筛选 按 BuyBox 状态
        if(isset($_POST['BuyBoxStatus'])&& $_POST['BuyBoxStatus']!= ''){
            $post_data['buyboxStatus'] = trim($_POST['BuyBoxStatus']);
        }

        // 筛选 按 BuyBox 发货类型
        if(isset($_POST['DespatchModeType'])&& $_POST['DespatchModeType']!= ''){
            $post_data['DespatchModeType'] = trim($_POST['DespatchModeType']);
        }

        // 筛选 按ASIN /  SellerSKU
        if(isset($_POST['ASINorSellerSKU']) && $_POST['ASINorSellerSKU']!= ''){
            $post_data['ASINorSellerSKU'] = trim($_POST['ASINorSellerSKU']);
        }

        // 筛选 按 店铺 id
        if(isset($_POST['MarketID']) && $_POST['MarketID']!= ''){
            $post_data['MarketID'] = trim($_POST['MarketID']);
        }

        $post_data['BangTuSecret'] =  "";

        $data['data']              = json_encode($post_data);

        $marketList                 = $this->request_post($url, $data);

        $marketList                 = trim($marketList);

        $state                      = explode('","',$marketList);

        $state                      = explode('":"',trim($state[0],'{'));

        $days_array                 = explode('"values":',$marketList);

        $days_array                 = trim($days_array[1],'}');

        $days_array                 = explode('},{',$days_array);

        $arr = Array();

        foreach($days_array as $key=>$value){
            $value = trim($value,'[{');
            $value = trim($value,'}]');
            $value = explode('","',$value);
            foreach($value as  $vo){
                $vo = explode('":"',$vo);
                $arr[$key][trim($vo[0],'"')] = trim($vo[1],'"');
            }
        }

        $count=count($arr);//得到数组元素个数

        $aser['data']  =  $this->pageSet($arr,'index.php?s=/home/index/getajaxproduct',$count,10,$page);// 赋值分页输出

        $aser['state'] =  $state[1];

        echo json_encode($aser);

        exit;
    }

    /**
     * 保存 商品 调价 调库存
     * @author xiaojing
     */
    public function saveProductAdjustment(){

        if (IS_POST) {

            $user_info = $this->userInfo();

            $url = 'http://120.76.102.10/webapi/save_amazon_price_or_quantity.php';

            $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

            $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

            $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

//            $post_data['BangTuSecret'] = I('post.BangTuSecret','');

            $post_data['MarketID'] = I('post.MarketID','');

            $post_data['SKU'] = I('post.SellerSKU','');

            if(isset($_POST['Price'])){
                $post_data['Price'] = I('post.Price','');
            }

            if(isset($_POST['Quantity'])){
                $post_data['Quantity'] = I('post.Quantity','');
            }

            $data['data'] = json_encode($post_data);

            $marketList = $this->request_post($url, $data);

            echo $marketList;
            exit;
        }
    }

    /**
     * 商品数据导出
     * @author xiaojing
     */
    public function exportProductData(){

        $user_info = $this->userInfo();

        $dataArr = json_decode(I('post.data'),true);

        $url = 'http://120.76.102.10/webapi/get_amazon_productlist_api.php';

        $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

        $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

        $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

        $page = empty($_POST['page']) ? 1 : $_POST['page'];

        // 筛选 按 产品 状态
        if(isset($_POST['ProductStatus']) && $_POST['ProductStatus']!= ''){
            $post_data['ProductStatus'] = trim($_POST['ProductStatus']);
        }

        // 筛选 按 产品  数量
        if(isset($_POST['Quantity'])&& $_POST['Quantity']!= ''){
            $post_data['Quantity'] = trim($_POST['Quantity']);
        }

        // 筛选 按 BuyBox 状态
        if(isset($_POST['BuyBoxStatus'])&& $_POST['BuyBoxStatus']!= ''){
            $post_data['buyboxStatus'] = trim($_POST['BuyBoxStatus']);
        }

        // 筛选 按 BuyBox 发货类型
        if(isset($_POST['DespatchModeType'])&& $_POST['DespatchModeType']!= ''){
            $post_data['DespatchModeType'] = trim($_POST['DespatchModeType']);
        }

        // 筛选 按ASIN /  SellerSKU
        if(isset($_POST['ASINorSellerSKU']) && $_POST['ASINorSellerSKU']!= ''){
            $post_data['ASINorSellerSKU'] = trim($_POST['ASINorSellerSKU']);
        }

        $post_data['BangTuSecret'] =  "";

        $post_data['MarketID'] =  $_POST['MarketID'];

        $data['data'] = json_encode($post_data);

        $marketList = $this->request_post($url, $data);

        $marketList = trim($marketList);

        $days_array = explode('"values":',$marketList);

        $days_array = trim($days_array[1],'}');

        $days_array = explode('},{',$days_array);

        $arr = Array();

        foreach($days_array as $key=>$value){
            $value = trim($value,'[{');
            $value = trim($value,'}]');
            $value = explode('","',$value);
            foreach($value as  $vo){
                $vo = explode('":"',$vo);
                $arr[$key][trim($vo[0],'"')] = trim($vo[1],'"');
            }
        }
        $dataArr = array();
        foreach($arr as $key=>$value){
            if($value['ProductStatus'] == 1){
                $dataArr[$key][0] = '可售';
            }else if($value['ProductStatus'] == 2){
                $dataArr[$key][0] = '不可售';
            }
            if($value['BuyBoxStatus'] == 1){
                $dataArr[$key][1] = '抢占';
            }else if($value['BuyBoxStatus'] == 2){
                $dataArr[$key][1] = '未抢占';
            }
            $dataArr[$key][2] = $value['SellerSKU'];
            $dataArr[$key][3] = $value['DespatchModeType'];
            $dataArr[$key][4] = $value['ASIN'];
            $dataArr[$key][5] = $value['ProductName'];
            $dataArr[$key][6] = $value['createtime'];
            $dataArr[$key][7] = $value['SaleReportIn30Days'];
            $dataArr[$key][8] = $value['Quantity'];
            $dataArr[$key][9] = $value['BuyBoxPrice'];
            $dataArr[$key][10] = $value['Price'];
        }

        $title = array('状态','Buybox状态','SKU','发货方式','ASIN','商品名称','创建日期','近30天出售','可售','Buybox价格','销售价格+配送费');
        $file_path = $this->exportFileCsv($dataArr,$title,'./Uploads/Product/');
        $resarr['url'] = 'http://'.$_SERVER['SERVER_NAME'].$file_path;
        $result = json_encode($resarr);
        echo $result;
        exit;
    }

    /**
     * 调价 记录  展示
     * @author xiaojing
     */
    public function getUserModifypricehistory(){

        $user_info = $this->userInfo();

        $dataArr = json_decode(I('post.data'),true);

        $url = 'http://120.76.102.10/webapi/get_usermodifypricehistory_api.php';

        $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

        $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

        $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

        // 筛选 按 产品 状态
        if(isset($_POST['MarketID']) && $_POST['MarketID']!= ''){
            $post_data['MarketID'] = trim($_POST['MarketID']);
        }

        // 筛选 按 产品  数量
        if(isset($_POST['ASIN'])&& $_POST['ASIN']!= ''){
            $post_data['ASIN'] = trim($_POST['ASIN']);
        }

        // 筛选 按 BuyBox 状态
        if(isset($_POST['ModifyPriceTime'])&& $_POST['ModifyPriceTime']!= ''){
            $post_data['ModifyPriceTime'] = trim($_POST['ModifyPriceTime']);
        }

        $data['data'] = json_encode($post_data);

        $marketList = $this->request_post($url, $data);

        $marketList = trim($marketList);

        $days_array = explode('"values":',$marketList);

        $days_array = trim($days_array[1],'}');

        $days_array = explode('},{',$days_array);

        $arr = Array();

        foreach($days_array as $key=>$value){
            $value = trim($value,'[{');
            $value = trim($value,'}]');
            $value = explode('","',$value);
            foreach($value as  $vo){
                $vo = explode('":"',$vo);
                $arr[$key][trim($vo[0],'"')] = trim($vo[1],'"');

            }
        }

        $count=count($arr);//得到数组元素个数

        return  $this->pageSet($arr,'index.php?s=/home/index/getajaxusermodifypricehistory',$count,20);// 赋值分页输出

    }

    /**
     * ajax 调价 记录  展示
     * @author xiaojing
     */
    public function getAjaxUserModifypricehistory(){

        $user_info = $this->userInfo();

        $dataArr = json_decode(I('post.data'),true);

        $url = 'http://120.76.102.10/webapi/get_usermodifypricehistory_api.php';

        $post_data['UserID'] = ($user_info['id'] != '') ? $user_info['id'] : "";

        $post_data['PasswordMD5'] = ($user_info['password'] != '')?$user_info['password'] : "";

        $post_data['UserName'] = ($user_info['email'] != '')?$user_info['email'] : "";

        $page = empty($_POST['page']) ? 1 : $_POST['page'];

        // 筛选 按 产品 状态
        if(isset($_POST['MarketID']) && $_POST['MarketID']!= ''){
            $post_data['MarketID'] = trim($_POST['MarketID']);
        }

        // 筛选 按 产品  数量
        if(isset($_POST['ASIN'])&& $_POST['ASIN']!= ''){
            $post_data['ASIN'] = trim($_POST['ASIN']);
        }

        // 筛选 按 BuyBox 状态
        if(isset($_POST['ModifyPriceTime'])&& $_POST['ModifyPriceTime']!= ''){
            $post_data['ModifyPriceTime'] = trim($_POST['ModifyPriceTime']);
        }

        $data['data'] = json_encode($post_data);

        $marketList = $this->request_post($url, $data);

        $marketList = trim($marketList);

        $days_array = explode('"values":',$marketList);

        $days_array = trim($days_array[1],'}');

        $days_array = explode('},{',$days_array);

        $arr = Array();

        foreach($days_array as $key=>$value){
            $value = trim($value,'[{');
            $value = trim($value,'}]');
            $value = explode('","',$value);
            foreach($value as  $vo){
                $vo = explode('":"',$vo);
                $arr[$key][trim($vo[0],'"')] = trim($vo[1],'"');

            }
        }

        $count=count($arr);//得到数组元素个数
        $aser['data'] =  $this->pageSet($arr,'index.php?s=/home/index/getajaxusermodifypricehistory',$count,20,$page);// 赋值分页输出
        echo json_encode($aser);
        exit;
    }


    //上传方法
    public function upload()
    {
        header("Content-Type:text/html;charset=utf-8");
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('xls', 'xlsx');// 设置附件上传类
        $upload->savePath  =      '/'; // 设置附件上传目录

        $info   =   $upload->uploadOne($_FILES['excelData']);// 上传文件
        $filename = './Uploads'.$info['savepath'].$info['savename'];
        $exts = $info['ext'];
        //print_r($info);exit;
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            $this->goods_import($filename, $exts);
        }
    }

    //导入数据页面
    public function import()
    {
        $this->display('goods_import');
    }

    //导入数据方法
    protected function goods_import($filename, $exts='xls')
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }else if($exts == 'xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        }


        //载入文件
        $PHPExcel = $PHPReader->load($filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet = $PHPExcel->getSheet(0);
        //获取总列数
        $allColumn = $currentSheet->getHighestColumn();
        //获取总行数
        $allRow = $currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=1; $currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $cell =$currentSheet->getCell($address)->getValue();
                //$cell = $data[$currentRow][$currentColumn];
                if($cell instanceof PHPExcel_RichText){
                    $cell = $cell->__toString();
                }
                print_r($cell);
            }

        }
        //$this->save_import($data);
    }

    //保存导入数据
    public function save_import($data)
    {
        //print_r($data);exit;

        $Goods = M('Goods');
        $add_time = date('Y-m-d H:i:s', time());
        foreach ($data as $k=>$v){
            if($k >= 2){
                $title=$v['A'];
                $info[$k-2]['title'] = $title;

                $old_pno=$v['E'];
                $info[$k-2]['old_PNO'] = $old_pno;

                $brand_title=$v['C'];
                $brand_id = M('Brand')->where(array('title' => $brand_title))->getField('id');
                if($brand_id){
                    $info[$k-2]['brand_id'] = $brand_id;
                }else{
                    $new_brand_id = M('Brand')->add(array('title' => $brand_title, 'sort' => $k, 'add_time' => $add_time));
                    $info[$k-2]['brand_id'] = $new_brand_id;
                }

                $price=$v['D'];
                $info[$k-2]['price'] = $price;

                $type_titles=$v['F'];
                $type_array = explode(',', $type_titles);

                foreach ($type_array as $type_info){
                    $type_title = $type_info;
                    $type_id = M('Type')->where(array('title' => $type_title))->getField('id');
                    if($type_id){
                        $info[$k-2]['type_ids'] .= $type_id.',';
                    }else{
                        $new_type_id = M('Type')->add(array('title' => $type_title, 'sort' => $k, 'add_time' => $add_time));
                        $info[$k-2]['type_ids'] .= ','.$new_type_id.',';
                    }

                }

                $category_title=$v['G'];
                $category_id = M('Category')->where(array('title' => $category_title))->getField('id');
                if($category_id){
                    $info[$k-2]['category_id'] = $category_id;
                }else{
                    $new_category_id = M('Category')->add(array('title' => $category_title, 'sort' => $k, 'add_time' => $add_time));
                    $info[$k-2]['category_id'] = $new_category_id;
                }

                $pno=$v['B'];
                $result = $Goods->where(array('PNO' => $pno))->find();

                //print_r($info[$k-2]);exit;
                if($result){
                    //更新操作
                    $result = $Goods->where(array('PNO' => $pno))->save($info[$k-2]);
                }else{
                    //入库操作
                    $info[$k-2]['PNO'] = $pno;
                    $info[$k-2]['add_time'] = $add_time;

                    $result = $Goods->add($info[$k-2]);
                }


                //print_r($info);exit;



            }

        }

        if(false !== $result || 0 !== $result){
            $this->success('产品导入成功', 'Admin/Goods/index');
        }else{
            $this->error('产品导入失败');
        }
        //print_r($info);

    }

    //导出数据方法
    protected function goods_export($goods_list=array())
    {

        $goods_list = $goods_list;
        $data = array();
        foreach ($goods_list as $k=>$goods_info){
            $data[$k][id] = $goods_info['id'];
            $data[$k][title] = $goods_info['title'];
            $data[$k][PNO] = $goods_info['PNO'];
            $data[$k][old_PNO] = $goods_info['old_PNO'];
            $data[$k][price]  = $goods_info['price'];
            $data[$k][brand_id]  = get_title('brand',$goods_info['brand_id']);
            $data[$k][category_id]  = get_title('category',$goods_info['category_id']);
            $data[$k][type_ids] = get_type_title($goods_info['id']);
            $data[$k][add_time] = $goods_info['add_time'];
        }

        //print_r($goods_list);
        //print_r($data);exit;

        foreach ($data as $field=>$v){
            if($field == 'id'){
                $headArr[]='产品ID';
            }

            if($field == 'title'){
                $headArr[]='产品名称';
            }

            if($field == 'PNO'){
                $headArr[]='零件号';
            }

            if($field == 'old_PNO'){
                $headArr[]='原厂参考零件号';
            }

            if($field == 'price'){
                $headArr[]='原厂参考面价';
            }

            if($field == 'type_ids'){
                $headArr[]='品牌';
            }

            if($field == 'brand_id'){
                $headArr[]='类别';
            }
            if($field == 'category_id'){
                $headArr[]='适用机型';
            }

            if($field == 'add_time'){
                $headArr[]='添加时间';
            }
        }

        $filename="goods_list";

        $this->getExcel($filename,$headArr,$data);
    }


    private  function getExcel($fileName,$headArr,$data){
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);

        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }


    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     * @author xiaojing
     */
    private function request_post($url = '', $post_data = array()) {

        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * 获取用户数据
     * @return mixed
     * @author xiaojing
     */
    public function userInfo(){
        $uid = query_user(array( 'uid'));
        $user_info = D('UcenterMember')->where('status=1 and id='.$uid['uid'])->find();
        return  $user_info;
    }

    /**
     * 分页
     * @param array $totalRows  总的记录数
     * @param array $listRows  每页显示记录数
     * @param array $parameter  分页跳转的参数
     * @param  int  $pass       当前页
     * @author xiaojing
     */
    public function pageSet($dataArr,$url,$totalRows, $listRows, $pages=1) {

        $rollPage   = 5;// 分页栏每页显示的页数

        $nowPage = $pages;

        $firstRow   = $listRows * ($pages - 1);

        $datalist = array_slice($dataArr,$firstRow,$listRows); //分页好的数

        /* 计算分页信息 */
        $totalPages = ceil($totalRows / $listRows); //总页数

        if(!empty($totalPages) && $nowPage > $totalPages) {
            $nowPage = $totalPages;
        }

        /* 计算分页零时变量 */
        $now_cool_page      = $rollPage/2;

        $now_cool_page_ceil = ceil($now_cool_page);

//        echo $now_cool_page_ceil;
        //上一页
        $up_row  = $nowPage - 1;

        $up_page = $up_row > 0 ?
            '<li class="paginate_button " aria-controls="dynamic-table" tabindex="0"><a href="javascript:void(0)" hrefs="'.$url.'" page="'.$up_row.'">&lt;</a></li>' :
            '<li class="paginate_button disabled" aria-controls="dynamic-table" tabindex="0"><a href="#">&lt;</a></li>';

        //下一页
        $down_row  = $nowPage + 1;
        $down_page = ($down_row <= $totalPages) ? '<li class="paginate_button " aria-controls="dynamic-table" tabindex="0"><a href="javascript:void(0)" hrefs="'.$url.'" page="'.$down_row.'">&gt;</a></li>' :
                                                    '<li class="paginate_button disabled" aria-controls="dynamic-table" tabindex="0"><a href="#">&gt;</a></li>';

        //第一页
        $the_first = '';
        if($totalPages > $rollPage && ($nowPage - $now_cool_page) >= 1){
            $the_first = '<li class="paginate_button previous" aria-controls="dynamic-table" tabindex="0" id="dynamic-table_previous">
                          <a href="javascript:void(0)" hrefs="'.$url.'" page="1"><i class="ace-icon fa fa-angle-double-left"></i></a></li>';
        }else if(!($nowPage - $now_cool_page) >= 1){
            $the_first = '<li class="paginate_button previous disabled" aria-controls="dynamic-table" tabindex="0" id="dynamic-table_previous">
                          <a href="#"><i class="ace-icon fa fa-angle-double-left"></i></a></li>';
        }

        //最后一页
        $the_end = '';
        if($totalPages > $rollPage && ($nowPage + $now_cool_page) < $totalPages){
            $the_end = '<li class="paginate_button next" aria-controls="dynamic-table" tabindex="0" id="dynamic-table_next">
            <a href="javascript:void(0)" hrefs="'.$url.'" page="'.$totalPages.'"><i class="ace-icon fa fa-angle-double-right"></i></a></li>';
        }

        //数字连接
        $link_page = "";
        for($i = 1; $i <= $rollPage; $i++){
            if(($nowPage - $now_cool_page) <= 0 ){
                $page = $i;
            }elseif(($nowPage + $now_cool_page - 1) >= $totalPages){
                $page = $totalPages - $rollPage + $i;
            }else{
                $page = $nowPage - $now_cool_page_ceil + $i;
            }
            if($page > 0 && $page != $nowPage){

                if($page <= $totalPages){
                    $link_page .= '<li class="paginate_button " aria-controls="dynamic-table" tabindex="0"><a href="javascript:void(0)" hrefs="'.$url.'" page="'.$page.'">' . $page . '</a></li>';
                }else{
                    break;
                }
            }else{
                if($page > 0 && $totalPages != 1){
                    $link_page .= '<li class="paginate_button active" aria-controls="dynamic-table" tabindex="0"><a href="#">'.$page.'</a></li>';
                }
            }
        }
        return array($nowPage, $up_page, $down_page, $the_first, $link_page, $the_end, $totalRows, $totalPages,$datalist);


    }

    /**
     * 数据 导出
     * @author xiaojing
     * @param $data 数据
     * @param $title_arr 头部标题
     * @param string $file_path  存储路径
     * @param string $file_name  文件名称   NOLL=当前时间
     * @param string $file_type 文件类型 格式=[.csv]
     * @return bool|strin
     */
    public function exportFileCsv($data, $title_arr,$file_path='/', $file_name = '',$file_type = '.csv') {

        $csv_data = '';

        $nums = count($title_arr);

        for ($i = 0; $i < $nums - 1; ++$i) {
            $csv_data .= '"' . $title_arr[$i] . '",';
        }

        if ($nums > 0) {
            $csv_data .= '"' . $title_arr[$nums - 1] . "\"\r\n";
        }

        foreach ($data as $k => $row) {
            for ($i = 0; $i < $nums - 1; ++$i) {
                $row[$i] = str_replace("\"", "\"\"", $row[$i]);
                $csv_data .= '"' . $row[$i] . '",';
            }
            $csv_data .= '"' . $row[$nums - 1] . "\"\r\n";
            unset($data[$k]);
        }
        $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
        $file_name = $file_path.$file_name.$file_type;
        $csv_data = iconv("utf-8", "gb2312", $csv_data);
        file_put_contents($file_name, $csv_data);
        return $file_name;
    }

    public function JSON($array) {
       $this->arrayRecursive($array, 'urlencode', true);
        $json = json_encode($array);
        return urldecode($json);
    }

    public function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
    {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $this->arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }
            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    }

    /*public  function  initMemcached(){
        //初始化
        S(array(
                'type'=>'memcache',// 缓存类型
                'host'=>'127.0.0.1', // 地址
                'port'=>'11211', //端口号
                'prefix'=>'51Memcache', // 缓存前缀
                'expire'=>60// 到期时长
            )
        );
       //设置
        S('serg','xiaofeng','3600');
        //获取数据
        // echo S('serg');
//        exit;
        //清空数据
//        S('username',null);
    }*/
}